// 微信小程序适配工具函数

/**
 * 判断当前运行环境
 */
export function getEnv() {
  // #ifdef MP-WEIXIN
  return 'mp-weixin'
  // #endif
  
  // #ifdef H5
  return 'h5'
  // #endif
  
  // #ifdef APP-PLUS
  return 'app-plus'
  // #endif
  
  return 'unknown'
}

/**
 * 判断是否为微信小程序环境
 */
export function isMiniProgram() {
  return getEnv() === 'mp-weixin'
}

/**
 * 获取系统信息
 */
export function getSystemInfo() {
  return new Promise((resolve, reject) => {
    uni.getSystemInfo({
      success: function(res) {
        resolve(res)
      },
      fail: function(error) {
        reject(error)
      }
    })
  })
}

/**
 * 小程序专用的页面跳转
 */
export function navigateTo(url, options = {}) {
  if (isMiniProgram()) {
    // 小程序环境下的特殊处理
    const { animationType = 'pop-in', animationDuration = 300 } = options
    
    return uni.navigateTo({
      url,
      animationType,
      animationDuration,
      success: options.success,
      fail: options.fail,
      complete: options.complete
    })
  } else {
    // 其他环境
    return uni.navigateTo({
      url,
      success: options.success,
      fail: options.fail,
      complete: options.complete
    })
  }
}

/**
 * 获取当前页面栈
 */
export function getCurrentPages() {
  return getCurrentPages() || []
}

/**
 * 小程序分享配置
 */
export function setupShare(options = {}) {
  if (!isMiniProgram()) {
    return
  }
  
  const defaultOptions = {
    title: '仓储管理系统',
    path: '/pages/index/index',
    imageUrl: '/static/share-image.png'
  }
  
  return {
    ...defaultOptions,
    ...options
  }
}

/**
 * 获取微信用户信息
 */
export function getUserInfo() {
  return new Promise((resolve, reject) => {
    if (!isMiniProgram()) {
      reject(new Error('非微信小程序环境'))
      return
    }
    
    uni.getUserInfo({
      success: function(res) {
        resolve(res)
      },
      fail: function(error) {
        reject(error)
      }
    })
  })
}

/**
 * 微信登录
 */
export function wxLogin() {
  return new Promise((resolve, reject) => {
    if (!isMiniProgram()) {
      reject(new Error('非微信小程序环境'))
      return
    }
    
    uni.login({
      provider: 'weixin',
      success: function(res) {
        resolve(res)
      },
      fail: function(error) {
        reject(error)
      }
    })
  })
}

/**
 * 微信登录并获取用户信息
 */
export async function wxLoginWithUserInfo() {
  try {
    // 1. 获取登录code
    const loginRes = await wxLogin()
    if (!loginRes.code) {
      throw new Error('获取微信登录code失败')
    }
    
    // 2. 获取用户信息
    const userInfoRes = await getUserInfo()
    if (!userInfoRes.userInfo) {
      throw new Error('获取用户信息失败')
    }
    
    return {
      code: loginRes.code,
      userInfo: userInfoRes.userInfo,
      encryptedData: userInfoRes.encryptedData,
      iv: userInfoRes.iv
    }
  } catch (error) {
    throw error
  }
}

/**
 * 检查登录状态
 */
export function checkLoginStatus() {
  const token = uni.getStorageSync('token')
  const userInfo = uni.getStorageSync('userInfo')
  
  return {
    isLoggedIn: !!(token && userInfo),
    token,
    userInfo,
    hasPhone: !!(userInfo && userInfo.phone)
  }
}

/**
 * 清除登录状态
 */
export function clearLoginStatus() {
  uni.removeStorageSync('token')
  uni.removeStorageSync('userInfo')
}

/**
 * 获取用户位置信息
 */
export function getLocation(type = 'wgs84') {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type,
      success: function(res) {
        resolve(res)
      },
      fail: function(error) {
        reject(error)
      }
    })
  })
}

/**
 * 选择图片
 */
export function chooseImage(options = {}) {
  const defaultOptions = {
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera']
  }
  
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      ...defaultOptions,
      ...options,
      success: function(res) {
        resolve(res)
      },
      fail: function(error) {
        reject(error)
      }
    })
  })
}

/**
 * 预览图片
 */
export function previewImage(urls, current = 0) {
  if (!Array.isArray(urls) || urls.length === 0) {
    return
  }
  
  uni.previewImage({
    urls,
    current: typeof current === 'number' ? urls[current] : current
  })
}

/**
 * 保存图片到相册
 */
export function saveImageToPhotosAlbum(filePath) {
  return new Promise((resolve, reject) => {
    if (!isMiniProgram()) {
      reject(new Error('该功能仅支持微信小程序'))
      return
    }
    
    uni.saveImageToPhotosAlbum({
      filePath,
      success: function(res) {
        resolve(res)
      },
      fail: function(error) {
        reject(error)
      }
    })
  })
}

/**
 * 设置剪贴板内容
 */
export function setClipboardData(data) {
  return new Promise((resolve, reject) => {
    uni.setClipboardData({
      data,
      success: function(res) {
        resolve(res)
      },
      fail: function(error) {
        reject(error)
      }
    })
  })
}

/**
 * 获取剪贴板内容
 */
export function getClipboardData() {
  return new Promise((resolve, reject) => {
    uni.getClipboardData({
      success: function(res) {
        resolve(res.data)
      },
      fail: function(error) {
        reject(error)
      }
    })
  })
}

/**
 * 扫码功能
 */
export function scanCode(options = {}) {
  const defaultOptions = {
    scanType: ['barCode', 'qrCode']
  }
  
  return new Promise((resolve, reject) => {
    uni.scanCode({
      ...defaultOptions,
      ...options,
      success: function(res) {
        resolve(res)
      },
      fail: function(error) {
        reject(error)
      }
    })
  })
}

/**
 * 获取网络状态
 */
export function getNetworkType() {
  return new Promise((resolve, reject) => {
    uni.getNetworkType({
      success: function(res) {
        resolve(res)
      },
      fail: function(error) {
        reject(error)
      }
    })
  })
}

/**
 * 监听网络状态变化
 */
export function onNetworkStatusChange(callback) {
  if (typeof callback === 'function') {
    uni.onNetworkStatusChange(callback)
  }
}

/**
 * 显示模态对话框
 */
export function showModal(options = {}) {
  const defaultOptions = {
    title: '提示',
    content: '',
    showCancel: true,
    cancelText: '取消',
    confirmText: '确定'
  }
  
  return new Promise((resolve, reject) => {
    uni.showModal({
      ...defaultOptions,
      ...options,
      success: function(res) {
        resolve(res)
      },
      fail: function(error) {
        reject(error)
      }
    })
  })
}

/**
 * 显示操作菜单
 */
export function showActionSheet(itemList) {
  return new Promise((resolve, reject) => {
    uni.showActionSheet({
      itemList,
      success: function(res) {
        resolve(res)
      },
      fail: function(error) {
        reject(error)
      }
    })
  })
}

/**
 * 小程序更新管理
 */
export function checkForUpdate() {
  if (!isMiniProgram()) {
    return
  }
  
  // #ifdef MP-WEIXIN
  const updateManager = uni.getUpdateManager()
  
  updateManager.onCheckForUpdate(function (res) {
    console.log('检查更新结果:', res.hasUpdate)
  })
  
  updateManager.onUpdateReady(function () {
    uni.showModal({
      title: '更新提示',
      content: '新版本已经准备好，是否重启应用？',
      success: function (res) {
        if (res.confirm) {
          updateManager.applyUpdate()
        }
      }
    })
  })
  
  updateManager.onUpdateFailed(function () {
    console.error('小程序更新失败')
  })
  // #endif
}

/**
 * 获取小程序启动参数
 */
export function getLaunchOptionsSync() {
  if (!isMiniProgram()) {
    return {}
  }
  
  // #ifdef MP-WEIXIN
  return uni.getLaunchOptionsSync()
  // #endif
  
  return {}
}

/**
 * 小程序性能监控
 */
export function createPerformanceObserver() {
  if (!isMiniProgram()) {
    return null
  }
  
  // #ifdef MP-WEIXIN
  return uni.createPerformanceObserver()
  // #endif
  
  return null
} 